package cn.lg.soar.message.service;

import cn.lg.soar.common.util.current.CurrentUser;
import cn.lg.soar.common.util.current.ThreadLocalHolder;
import cn.lg.soar.common.util.token.SoarJWT;
import cn.lg.soar.core.util.SoarSubscriber;
import cn.lg.soar.system.api.model.RefreshTokenDTO;
import cn.lg.soar.system.api.service.IRefreshTokenApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * websocket服务
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ServerEndpoint(value = "/message/ws")
public class WebSocket  {
    protected static final Logger logger = LoggerFactory.getLogger(WebSocket.class);

    private static IRefreshTokenApi refreshTokenApi;
    private static WebSocketManager manager;

    static {
        SoarSubscriber.subscribeRunner(a -> {
            refreshTokenApi = a.getBean(IRefreshTokenApi.class);
            manager = a.getBean(WebSocketManager.class);
        });
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> list = params.get("token");
        if (list == null) {
            session.close();
            logger.info("验证失败，关闭连接：{}", session.getId());
            return;
        }
        String token = list.get(0);
        Object[] payload = SoarJWT.parsePayload(token, Object[].class);
        CurrentUser currentUser = CurrentUser.valueOf(payload);
        String tokenId = currentUser.getTokenId();
        RefreshTokenDTO refreshToken = refreshTokenApi.getById(tokenId);
        if (refreshToken != null && LocalDateTime.now().isBefore(refreshToken.getTokenExpires())) {
            ThreadLocalHolder.setCurrentUser(currentUser);
            manager.onOpen(currentUser.getId(), tokenId, session);
        } else {
            session.close();
            logger.info("验证失败，关闭连接：{}", session.getId());
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        manager.onClose(session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        manager.onMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        manager.onError(session, error);
    }

}
